package com.szh.taobaounion.Presenter.impl;

import com.szh.taobaounion.Presenter.ICategoryPagerPresenter;
import com.szh.taobaounion.model.Api;
import com.szh.taobaounion.model.domain.HomePagerContent;
import com.szh.taobaounion.utils.LogUtils;
import com.szh.taobaounion.utils.RetrofitManager;
import com.szh.taobaounion.utils.UrlUtils;
import com.szh.taobaounion.view.ICategoryPagerCallBack;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ICatregoryPagerPresentImpl implements ICategoryPagerPresenter {
    private Map<Integer, Integer> pageInfo = new HashMap<>();
    public static final int DEFAULT_PAGE = 1;
    private Integer mCurrentPage;
    private Integer targetPage;

    @Override
    public void getcontentByCategoryId(int categoryId) {
        for (ICategoryPagerCallBack callBack : callBacks) {
            if (callBack.GetCategoryId() == categoryId) {
                callBack.onLoading();
            }
        }
        //根据分类Id加载内容
        //TODO:
        targetPage = pageInfo.get(categoryId);
        if (targetPage == null) {
            targetPage = DEFAULT_PAGE;
            pageInfo.put(categoryId, targetPage);
        }
        Call<HomePagerContent> task = CreateTask(categoryId, targetPage);
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                int code = response.code();
                LogUtils.d(ICatregoryPagerPresentImpl.this, "homepagercode--->" + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerContent pagerContent = response.body();
                    //LogUtils.d(CatregoryPagerPresentImpl.this,"pagerContent----->"+pagerContent);
                    //通知Ui层更新数据
                    handleHomePageContentResult(pagerContent, categoryId);
                } else {
                    handleErrorNetwork(categoryId);
                }
            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                LogUtils.d(ICatregoryPagerPresentImpl.this, "onFailure--->" + t.toString());
            }
        });

    }

    private Call<HomePagerContent> CreateTask(int categoryId, Integer targetPage) {
        String homePagerUrl = UrlUtils.createHomePagerUrl(categoryId, targetPage);
        LogUtils.d(this, "homePagerUrl---->" + homePagerUrl);
        Retrofit retrofit = RetrofitManager.getInstance().getmRetrofit();
        Api api = retrofit.create(Api.class);
        return api.getHomePagerContent(homePagerUrl);
    }

    private void handleErrorNetwork(int categoryId) {
        for (ICategoryPagerCallBack callBack : callBacks) {
            if (callBack.GetCategoryId() == categoryId) {
                callBack.onError();
            }
        }
    }

    private void handleHomePageContentResult(HomePagerContent pagerContent, int categoryId) {
        //通知Ui层更新数据
        List<HomePagerContent.DataBean> data = pagerContent.getData();
        for (ICategoryPagerCallBack callBack : callBacks) {
            if (callBack.GetCategoryId() == categoryId) {
                if (pagerContent == null || pagerContent.getData().size() == 0) {
                    callBack.onEmpty();
                } else {
                    List<HomePagerContent.DataBean> looperData = data.subList(data.size() - 5, data.size());
                    callBack.onLoderLooperListLoaded(looperData);
                    callBack.onContentLoaded(data);
                }
            }
        }
    }

    @Override
    public void lodeMore(int categoryId) {
        //加载更多的数据
        //1、拿到当前页面
        //2、页码++
        targetPage++;
        //3、加载数据

        Call<HomePagerContent> task = CreateTask(categoryId,targetPage);
        //4、处理数据结果
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call,Response<HomePagerContent> response) {
                //结果
                int code = response.code();
                LogUtils.d(ICatregoryPagerPresentImpl.this,"result code -- > " + code);
                if (targetPage <= 10) {


                if(code == HttpURLConnection.HTTP_OK) {
                    HomePagerContent result = response.body();
                    // LogUtils.d(CategoryPagePresenterImpl.this,"result -- > " + result.toString());
                        handleLoderResult(result,categoryId);

                } else {
                    handleErrorNetwork(categoryId);
                }
             }else {
                    handleLoaderMoreEmpty(categoryId);
                }
            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                //失败
                handleLoderMoreErrorNetwork(categoryId);
                LogUtils.d(ICatregoryPagerPresentImpl.this, t.toString());
            }
        });
    }

    private void handleLoaderMoreEmpty(int categoryId) {
        for (ICategoryPagerCallBack callBack : callBacks) {
            if (callBack.GetCategoryId() == categoryId) {
                callBack.onLoderMoreEmpty();
            }
        }
    }

    private void handleLoderResult(HomePagerContent result, int categoryId) {
        for (ICategoryPagerCallBack callBack : callBacks) {
            if (callBack.GetCategoryId() == categoryId) {
                if (result == null||result.getData().size()==0) {
                    callBack.onLoderMoreEmpty();
                }else {
                      callBack.onLoderMoreLoaded(result.getData());
                }
            }
        }
    }

    private void handleLoderMoreErrorNetwork(int categoryId) {
          mCurrentPage--;
          pageInfo.put(categoryId,mCurrentPage);
        for (ICategoryPagerCallBack callBack : callBacks) {
            if (callBack.GetCategoryId() == categoryId) {
                callBack.onLoderMoreError();
            }
        }
    }

    @Override
    public void reLode(int categoryId) {

    }

    private List<ICategoryPagerCallBack> callBacks = new ArrayList<>();

    @Override
    public void registerViewCallBack(ICategoryPagerCallBack callBack) {
        if (!callBacks.contains(callBack)) {
            callBacks.add(callBack);
        }
    }

    @Override
    public void unregisterViewCallBack(ICategoryPagerCallBack callBack) {
        callBacks.remove(callBack);
    }
}
